package com.benchmark.springboot.controller;

import com.benchmark.springboot.enums.ErrorCodeEnum;
import com.benchmark.springboot.job.CpuHighJob;
import com.benchmark.springboot.quartz.JobResult;
import com.benchmark.springboot.quartz.ScheduleJob;
import com.benchmark.springboot.quartz.factory.DynamicJobFactory;
import com.power.common.constants.BaseErrorCode;
import com.power.common.model.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 获取cpu信息
 *
 * @author yu 2019/9/3.
 */
@Slf4j
@RestController
@RequestMapping("cpu")
public class CpuController {

    private static final String CPU_JOB = "com.benchmark.springboot.job.CpuHighJob";

    @Resource
    private DynamicJobFactory dynamicJobFactory;

    /**
     * 获取cpu数
     *
     * @return
     */
    @GetMapping("/cores")
    public CommonResult<String> getCores() {
        int cores = Runtime.getRuntime().availableProcessors();
        return CommonResult.ok().setResult("cup cores=" + cores);
    }

    /**
     * cpu占用100%模拟
     *
     * @return
     */
    @GetMapping("/startHighMock")
    public CommonResult startHighMock() {
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setClassName(CPU_JOB);
        scheduleJob.setChineseName("模拟CPU占用100%");
        scheduleJob.setUniqueKey(CPU_JOB + "_rest");
        try {
            JobResult jobResult = dynamicJobFactory.addNowRunJob(scheduleJob, null);
            if (!jobResult.isSuccess()) {
                return CommonResult.fail(ErrorCodeEnum.JOB_ERROR.getCode(), jobResult.getMessage());
            }
        } catch (Exception e) {
            log.error("启动cpu占用100%模拟任务报错", e);
            return CommonResult.fail(BaseErrorCode.Common.UNKNOWN_ERROR);
        }
        return CommonResult.ok();
    }

    /**
     * 停止cpu占用100%模拟
     *
     * @return
     */
    @GetMapping("/stopHighMock")
    public CommonResult stopHighMock() {
        try {
            dynamicJobFactory.stop(CPU_JOB);
        } catch (Exception e) {
            log.error("停止cpu占用100%模拟任务报错了", e);
            return CommonResult.fail(BaseErrorCode.Common.UNKNOWN_ERROR);
        }
        return CommonResult.ok();
    }
}
